/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.ocm.burnningstar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

import com.ocm.burnningstar.Model.CheckModel;
import com.ocm.burnningstar.Utils.Helper;
import com.ocm.burnningstar.View.ClassXFragment;
import com.ocm.burnningstar.View.CourseFragment;
import com.ocm.burnningstar.View.FreeFragment;
import com.ocm.burnningstar.View.OverFragment;
import com.shape.sdk.Course;
import com.shape.sdk.Fitness;
import com.shape.sdk.FitnessData;
import com.shape.sdk.ShapeCenter;
import com.wandoujia.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.x;

import java.security.NoSuchAlgorithmException;
import java.util.List;

/*
 * MainActivity class that loads MainFragment
 */
@ContentView(R.layout.activity_main)
public class MainActivity extends Activity {
    String TAG = "MAIN";

    Interface.ReadeyListener readycb;
    Interface.ClassListener classcb;
    Interface.CourseListener coursecb;
    Interface.OverListener overcb;


    public void SetReadyListener(Interface.ReadeyListener listener){
        readycb = listener;
    }

    public void SetClassListener(Interface.ClassListener listener){
        classcb = listener;
    }

    public void SetCourseListener(Interface.CourseListener listener){
        coursecb = listener;
    }

    public void SetOverListener(Interface.OverListener listener){
        overcb = listener;
    }

    private String pathFile = Environment.getRootDirectory()+"/sdcard";

    boolean isActive = false;
    final int freeFragmentID = 1;
    Handler handler;
    ShapeCenter shapeCenter;
    Fitness fitness;
    int perpareCount = 0;
    int runningCount = 0;
    public static int MAX_COUNT = 60*1000;
    //结算后返回到空闲状态的时间
    int time_end2start = 15*1000;
    long DEFAULT_SHOW_TIME = 2*60*1000;


    Course course;
    long courseStartTime = 0;
    long courseStopTime = 0;
    int workingCount = 0;
    long currentVideoDuration = 0;
    int currentVideoPlayNum = 0;
    List<Course.VideoUnit> playList = null;
    CheckModel checkModel=null;
    Gson gson = new Gson();

    final static long MINUTES_15 = 15 * 60 * 1000;
    final static long STOP_SHOW_TIME = 2*60*1000;
    public static long READY_TIME = 6000;

    public Fragment mFragment;
    boolean IsOver = false;
    boolean DEBUG = false;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE" ,"android.permission.INTERNET"};
    //操课
    public static ClassXFragment classFragment = new ClassXFragment();
    //空闲
    public static FreeFragment freeFragment = new FreeFragment();
    //圈课
    public static CourseFragment courseFragment = new CourseFragment();
    //结算
    public static OverFragment overFragment = new OverFragment();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);

//        shapeCenter.init(storeId, stationId, stationCount,shapeListener);
        verifyStoragePermissions(this);
        getDefaultParams();
        init();
//        if(!isActive){
//            showInputDialog();
//        }else{
//            init();
//        }
    }
    EditText editText;
    private void showInputDialog() {
    /*@setView 装入一个EditView
     */
        if(editText==null)editText= new EditText(MainActivity.this);
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(MainActivity.this);
        inputDialog.setTitle("请输入激活码").setView(editText);
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        CheckInfo();
                    }
                }).show();
    }

    public static void verifyStoragePermissions(Activity activity) {
        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.READ_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void getDefaultParams(){
        SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.app_name),0);
        isActive = sharedPreferences.getBoolean("isActive",false);
    }
    public boolean saveDefaultParams(){
        SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.app_name),0);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("isActive",true);
        return editor.commit();
    }
    public void CheckInfo(){
        Log.i(TAG,"ShopInfo");
        String strUrl = "https://smartgymdemo.ocmcom.com/api/YunxinApi/activation";
        final Activity that = this;
        RequestParams params = new RequestParams(strUrl);
        params.setMultipart(true);
        params.setMethod(HttpMethod.POST);
        String uid = Helper.getUniqueId(this);
        Log.i("zjy","uid:"+uid);
        params.addParameter("sn", uid);
        params.addParameter("activation_code", editText.getText().toString());
        try {
            params.addParameter("sign", Helper.toMD5(uid+"ocm"));
        } catch (NoSuchAlgorithmException e) {
            params.addParameter("sign", "");
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.i(TAG,result);
                try{
                    checkModel = gson.fromJson(result, CheckModel.class);
                    if(checkModel==null||!checkModel.flag){
                        Toast.makeText(that,"激活失败",Toast.LENGTH_SHORT);
                        showInputDialog();
                    }else{
                        if(saveDefaultParams()){
                            Toast.makeText(that,"激活成功",Toast.LENGTH_SHORT);
                            init();
                        }else{
                            Toast.makeText(that,"激活成功",Toast.LENGTH_SHORT);
                            saveDefaultParams();
                            showInputDialog();
                        }

                    }
                }catch (Exception e){
                    int startIdx = result.indexOf("msg")+6;
                    int endIdx = result.indexOf (',',startIdx)-1;
                    String msg = Helper.unicodeToString(result.substring(startIdx,endIdx));
                    Log.e(TAG, msg);
                    Toast.makeText(that,msg,Toast.LENGTH_SHORT);
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {
            }
        });
    }

    ShapeCenter.Listener shapeListener = new ShapeCenter.Listener() {
        @Override
        public void onEvent(ShapeCenter.PublicNotifyType type, long doTimestamp) {
            Log.d("shapesdk", "ON EVENT " + type  );
            long delay;
            long systime = System.currentTimeMillis();
            switch (type) {
                case START:
                    Log.i("timecheck","systime:"+systime+",doTimestamp:"+doTimestamp);
                    delay = doTimestamp - systime;
                    READY_TIME = delay/1000;
                    READY_TIME = READY_TIME>0?READY_TIME:1;
                    IsOver = false;
                    start(System.currentTimeMillis());
//                    if (delay > 0) {
//                        handler.postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                if (fitness != null && fitness.getState() == Fitness.State.READY) {
//                                    IsOver = false;
//                                    start(System.currentTimeMillis());
//                                }
//                            }
//                        }, delay);
//                    } else {
//                        IsOver = false;
//                        start(System.currentTimeMillis());
//                    }
                    break;
                case STOP:
                    delay = doTimestamp - systime;
                    Log.i("FAKE","DEFAULT_SHOW_TIME:"+delay);
                    stop(systime);
                    goOver();
                    DEFAULT_SHOW_TIME = delay;
//                    if (delay > 0) {
//                        handler.postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                if (fitness != null && fitness.getState() == Fitness.State.RUNNING) {
//                                    stop(System.currentTimeMillis());
//                                }
//                            }
//                        }, delay);
//                    } else {
//                        stop(System.currentTimeMillis());
//                    }
                    break;
                case PAUSE:
                    // do nothing
                    break;
                case RESUME:
                    // do nothing
                    break;
                default:
                    throw new RuntimeException();
            }
        }
    };
    private void working() {
        // 5 秒检查一次状态
        if (workingCount % 5 == 0) {
            stateCheck();
        }

        // 2 秒刷新一次数据
        if (workingCount % 2 == 0) {
            refreshData();
        }

        ++workingCount;
        if (workingCount == 10) {
            workingCount = 0;
        }
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                working();
            }
        }, 1000);
    }

    private void stateCheck() {
        if (course == null) {
            // 上节课刚结束或者刚刚开机
            course = shapeCenter.getNextCourse();
        }
        if (course == null) {
            Log.d("shapesdk", "no course");
            return;
        }
        if (fitness == null) {
            fitness = shapeCenter.loadCourse(course);
            Log.d("shapesdk", "load course: " + course.getScheduleId());
        }
        if (fitness == null) {
            // 异常情况 不可能
            throw new RuntimeException();
        }

        long currentTime = System.currentTimeMillis();
        switch (fitness.getState()) {
            case INIT:
                // 异常情况 不可能
                throw new RuntimeException();
            case READY:
                // 判断是否该课程已经过了开始时间
                // 在该时间段可以访问链接开始课程
                // http://fit.runninglemon.com/api/v1/coach/test_start?store_id=1
                // 可以通过下面这个链接添加签到的用户, 其中 xxx 是字符串，每个用户需要不同
                // http://fit.runninglemon.com/api/v1/booking/test_bind?device_id=xxxx
                // Warning getStartTime 的单位都是毫秒
                IsOver = false;
                if (currentTime > course.getStartTime() + MINUTES_15) {
                    stop(currentTime);
                    Log.d("shapesdk", "this course not start and stop it : " + course.getScheduleId());
                }
                break;
            case RUNNING:
                // 判断是否该课程已经结束
                // 在该时间段可以访问链接结束课程
                // http://fit.runninglemon.com/api/v1/coach/test_finish?store_id=1
                IsOver = false;
                Log.i(TAG,"getDuration()"+course.getDuration());
//                if (currentTime > courseStartTime + course.getDuration() * 1000+READY_TIME*1000) {
//                    stop(currentTime);
//                    Log.d("shapesdk", "this course stop by auto : " + course.getScheduleId());
//                }
                break;
            case PAUSE:
                // 异常情况 不可能
                throw new RuntimeException();
            case STOP:
                Log.d("shapesdk", "stateCheck STOP "+ (currentTime-courseStopTime));
                // 判断结束展示时间是否结束，结束后进度下一节课
                // 在该时间段可以访问链接结束课程
                // http://fit.runninglemon.com/api/v1/coach/test_finish?store_id=1
                if (currentTime -courseStopTime > DEFAULT_SHOW_TIME) {
                    innerfinish();
                }
                break;
        }
    }

    private void innerfinish() {
        course = null;
        fitness = null;
        courseStartTime = 0;
        courseStopTime = 0;
        currentVideoDuration = 0;
        currentVideoPlayNum = 0;
        playList = null;
    }
    //关闭课程视频等并跳转到结算页
    void goOver(){
        Log.i("fitness","goOver");
        IsOver = true;
        final List<FitnessData> showFitnessDatas = fitness.getResultReport();
        overFitnessDatas = showFitnessDatas;
        if(mFragment==classFragment||mFragment==courseFragment)switchContent(mFragment,overFragment);
        if(classcb!=null){
            classcb.over();
        }
        if(coursecb!=null)coursecb.over();
    }

    void  init(){
        shapeCenter = new ShapeCenter(getApplicationContext());
        shapeCenter.init(shapeListener);
        handler = new Handler(Looper.getMainLooper());
        PostRunning();
        courseFragment.SetNextListener(new CourseFragment.NextListener() {
            @Override
            public void ClassOver() {
                Log.i("zjy","ClassOver");
                stop(System.currentTimeMillis());
                DEFAULT_SHOW_TIME = STOP_SHOW_TIME;
            }
            @Override
            public void GoNext() {
            }
        });

        classFragment.SetNextLisenter(new ClassXFragment.NextLisenter() {
            @Override
            public void GoNext() {
                fitness.next();
                Log.d("shapesdk", "next !!!!!");
            }

            @Override
            public void ClassOver() {
                Log.i("zjy","ClassOver");
                stop(System.currentTimeMillis());
                DEFAULT_SHOW_TIME = STOP_SHOW_TIME;
            }
        });
        working();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        getFragmentManager().beginTransaction().replace(R.id.container, freeFragment).commit();
        mFragment = freeFragment;
    }

    private void start(long currentTime) {
        Log.i("fitness","start");
        if (fitness == null || fitness.getState() != Fitness.State.READY) {
            return;
        }
        fitness.start();
        courseStartTime = currentTime;
    }

    public static List<FitnessData> overFitnessDatas;

    private void refreshData() {
        if (course == null || fitness == null) {
            // 没有加载出任何内容，返回
            return;
        }
        switch (fitness.getState()) {
            case INIT:
                // 异常情况 不可能
                throw new RuntimeException();
            case READY:
                Log.i("shapesdk","refreshData READY");
                List<FitnessData> readyFitnessDatas = fitness.getUsersFitness();
                if (readyFitnessDatas == null || readyFitnessDatas.size() == 0) {
                    Log.d("shapesdk", "no users");
                    return;
                }
                if(mFragment!=freeFragment)switchContent(mFragment,freeFragment);
                if(readycb!=null)readycb.run(readyFitnessDatas);
                break;
            case RUNNING:
                Log.i("shapesdk","refreshData RUNNING");
//                if (fitness.getState() == Fitness.State.RUNNING) {
//                    nextLogic(System.currentTimeMillis());
//                }
//                List<FitnessData> showFitnessDatas = fitness.getUsersFitness();
//                if (showFitnessDatas == null || showFitnessDatas.size() == 0) {
//                    Log.d("shapesdk", "no users");
//                } else {
                    // TODO 1cm 显示这些数据到卡片
//                    for (FitnessData fitnessData : showFitnessDatas) {
//                        Log.d("shapesdk", fitness.getState() + " user :" + fitnessData.getUser().getUserId()
//                                + " heartRate:" + fitnessData.getHeartRate()
//                                + " calories:" + fitnessData.getCalories());
//                    }

                    int classType =course.getType();
                    List<FitnessData> runFitnessDatas = fitness.getUsersFitness();
                    if(classType==1||classType==3){
                        //操课
                        switchContent(freeFragment,courseFragment,mFragment!=courseFragment&&mFragment!=overFragment);
                        courseFragment.setCourseData(course);
                        if(coursecb!=null) coursecb.run(runFitnessDatas);
                    }else{
                        //圈课
                        switchContent(freeFragment,classFragment,mFragment!=classFragment&&mFragment!=overFragment);
                        classFragment.setClassData(course);
                        if(classcb!=null)classcb.run(runFitnessDatas);
                    }
//                }
            break;
            case PAUSE:
                // 异常情况 不可能
                throw new RuntimeException();
            case STOP: {
                Log.i("refreshData","STOP");
//                List<FitnessData> overFitnessDatas = fitness.getResultReport();
//                for (FitnessData fitnessData : overFitnessDatas) {
//                    // Warning getCalories 小卡，换算成显示的卡路里需要除以1000
//                    Log.d("shapesdk", "STOP user :" + fitnessData.getUser().getUserId()
//                            + " heartRate:" + fitnessData.getHeartRate()
//                            + " calories:" + fitnessData.getCalories());
//                }
                goOver();
            }
            break;
        }
    }
    private void stop(long currentTime) {
        if (fitness == null || fitness.getState() == Fitness.State.STOP) {
            return;
        }
        // Warning 接口发生了变化，原来的 finish 变成了 stop
        fitness.stop();
        courseStopTime = currentTime;
    }

    public void switchContent(Fragment from, Fragment to,boolean enable) {
        if(enable)switchContent(from,to);
    }

    public void switchContent(Fragment from, Fragment to) {
        FragmentTransaction transaction = getFragmentManager().beginTransaction().
                setCustomAnimations(R.animator.fragment_slide_left_enter,
                        R.animator.fragment_slide_left_exit,R.animator.fragment_slide_right_enter,R.animator.fragment_slide_right_exit);
        mFragment = to;
        getFragmentManager().beginTransaction().replace(R.id.container, to).commit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        Log.i("zjy","onBackPressed");
        stop(System.currentTimeMillis());
        DEFAULT_SHOW_TIME = 10*1000;
//        stop(System.currentTimeMillis());
    }



    void PostRunning(){
        String strUrl = "https://www.baidu.com";
        RequestParams params = new RequestParams(strUrl);
        params.setMultipart(true);
        params.setMethod(HttpMethod.POST);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
//                Log.i(TAG,result);
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i(TAG,"error"+ex.getMessage());
            }
            @Override
            public void onCancelled(CancelledException cex) { }
            @Override
            public void onFinished() {}
        });
    }

}
